/*
    OtaSwfUploader.js
    Copyright (c) Otávio Ribeiro<otavio@otavio.eng.br> @ 2008
    
    This file is part of OtaSwfUploader application.

    Birthday is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    Birthday is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

var OtaSwfUploader = function(cfg){
	this.init(cfg);
}

if(!OtaSwfUploader.instances)
	OtaSwfUploader.instances = {};


if(!window.getOtaSwfUploaderInstances){
	window.getOtaSwfUploaderInstances = function(instanceName){
		return OtaSwfUploader.instances[instanceName];
	}
}

OtaSwfUploader.status_code = {
	STATUS_ERROR: 1,
	IO_ERROR: 2,
	SECURITY_ERROR: 3,
	OPEN: 4,
	PROGRESS: 5,
	COMPLETE: 6,
	UPLOAD_COMPLETE: 7
};

OtaSwfUploader.file_status = {
	STATUS_PENDING: 0,
	STATUS_UPLOADING: 1,
	STATUS_REMOVED: 2,
	STATUS_COMPLETED: 3,
	STATUS_ERROR: 4,
	STATUS_UPLOAD_COMPLETED: 5
};

OtaSwfUploader.prototype.init = function(cfg)
{
	this.configurations = {
		width: 100,
		height: 100,
		buttonLabel: "Adicionar Arquivos",
		mainId: "upload_button_id",
		postUrl: "",
		allowMultiplesFiles: false,
		flashClassId: "clsid:d27cdb6e-ae6d-11cf-96b8-444553540000",
		flashCodeBase: "https://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0",
		javaClassId: "clsid:CAFEEFAC-0016-0000-0000-ABCDEFFEDCBA",
		javaCodeBase: "http://java.sun.com/update/1.6.0/jinstall-6u10-windows-i586.cab",
		basePath: "",
		useJavaClient: false,
		windowMode: "transparent",
		imageFieldName: "image"
	};
	
	for(i in cfg){
		if(this.configurations[i] != undefined){
			this.configurations[i] = cfg[i];
		}
	}
	
	this.mainId = this.configurations["mainId"];
	this.width = this.configurations["width"];
	this.height = this.configurations["height"];
	this.mainDivElement = document.getElementById(this.mainId);
	if(!this.mainDivElement){
		throw("Invalid main div element.");
	}
	
	this.mainDivElement.style.width = this.width + "px";
	this.mainDivElement.style.height = this.height + "px";
	
	this.movieName = "otaswfuploader_"+this.mainId;
	
	OtaSwfUploader.instances[this.movieName] = this;
}

OtaSwfUploader.prototype.enableJavaPlugin = function(value)
{
	this.configurations["useJavaClient"] = value;
}

OtaSwfUploader.prototype.isJavaPlugin = function()
{
	return this.configurations["useJavaClient"];
}

OtaSwfUploader.prototype.renderUploadObject = function()
{
	this._createFlash();
}

OtaSwfUploader.prototype._getFlashObject = function()
{
	var flashObject = document.getElementById(this.movieName);
	if(!flashObject){
		throw "Invalid flash object";
	}
	
	return flashObject;
}

OtaSwfUploader.prototype._clearMainDivElement = function()
{
	while(this.mainDivElement.childNodes.length > 0){
		this.mainDivElement.removeNode(0);
	}
}

OtaSwfUploader.prototype._createFlash = function()
{
	var container = document.createElement("DIV");
	container.style.width = this.width + "px";
	container.style.height = this.height + "px";
	container.style.overflow = "hidden";	
	
	this._clearMainDivElement();
	this.mainDivElement.appendChild(container);
	
	if(this.configurations["useJavaClient"]){
		container.innerHTML = this._getJavaHTML();	
	} else {
		container.innerHTML = this._getFlashHTML();	
	}	
}

OtaSwfUploader.prototype._getJavaHTML = function()
{
	var java_file = this.configurations["basePath"] + "/OtaJavaUploader.jar";
	
	var str = "";
	var _app = navigator.userAgent.toLowerCase();
	if(_app.indexOf("msie") > 0){
		str = ['<object codebase="http://java.sun.com/update/1.6.0/jinstall-6-windows-i586.cab#Version=6,0,0,99" classid="clsid:CAFEEFAC-0016-0000-0000-ABCDEFFEDCBA" id="', this.movieName,'" width="',this.width,'" height="',this.height,'">',
					'<param name="archive" value="',java_file,'"/>',
					'<param name="code" value="OtaJavaUploader"/>',
					'<param name="JAVA_CODEBASE" value="data"/>',
					'<param name="type" value="application/x-java-applet;version=1.6"/>',
					'<param name="mayscript" value="true"/>',
					this._getJavaParameters(1),
				'</object>'].join("");
	} else {
		str = ['<object classid="java:OtaJavaUploader" codebase="data" type="application/x-java-applet;version=1.6" id="', this.movieName,'" archive="',java_file,'" width="',this.width,'" height="',this.height,'">',
					'<param name="archive" value="',java_file,'"/>',
					'<param name="code" value="OtaJavaUploader"/>',
					'<param name="JAVA_CODEBASE" value="data"/>',
					'<param name="type" value="application/x-java-applet;version=1.6"/>',
					'<param name="mayscript" value="true"/>',
					this._getJavaParameters(1),
				'</object>'].join("");
	}
	return str;
}

OtaSwfUploader.prototype._getFlashHTML = function()
{	
	var flash_file = this.configurations["basePath"] + "/OtaSwfUploader.swf?random=" + Math.random() + "&timestamp=" + new Date().getDate();
	
	var str = "";
	var _app = navigator.userAgent.toLowerCase();
	
	if(_app.indexOf("msie") > 0){
	  str = ['<object type="application/x-shockwave-flash" id="', this.movieName,'" data="',flash_file,'" width="',this.width,'" height="',this.height,'">',
			  '<param name="movie" value="',flash_file,'"/>',
			  '<param name="quality" value="high"/>',
			  '<param name="allowFullScreen" value="true"/>',
			  '<param name="menu" valeu="false"/>',
			  '<param name="allowScriptAccess" value="always"/>',
			  '<param name="wmode" value="',this.configurations["windowMode"],'"/>',
			  '<param name="flashvars" value="',this._getParameters(),'"/>',
			  '</object>'].join("");
	} else {
	  str = ['<embed src="',flash_file,'" type="application/x-shockwave-flash" quality="high" ',
			  ' allowFullScreen="false" menu="false" ',
			  ' allowScriptAccess="always" wmode="',this.configurations["windowMode"],'" ',
			  ' flashvars="',this._getParameters(),'" id="',this.movieName,'" width="',this.width,'" height="',this.height,'" play="true" pluginspage="http://www.macromedia.com/go/getflashplayer"/>'].join("");
	}
	
	return str;
}

OtaSwfUploader.prototype._getJavaParameters = function(type)
{
	var str = "";
	
	if(type == 1){
		str = ['<param name="movieName" value="', this.movieName,'"/>',
					'<param name="buttonLabel" value="', this.configurations["buttonLabel"],'"/>',
					'<param name="postUrl" value="',this.configurations["postUrl"],'"/>',
					'<param name="allowMultiplesFiles" value="',(this.configurations["allowMultiplesFiles"]?"true":"false"),'"/>',
					'<param name="imageFieldName" value="',this.configurations["imageFieldName"],'"/>',
				   ].join("");
	} else {
		str = ['movieName="', this.movieName,'"',
				' buttonLabel="', this.configurations["buttonLabel"],'"',
				' postUrl="',this.configurations["postUrl"],'"',
				' allowMultiplesFiles="',(this.configurations["allowMultiplesFiles"]?"true":"false"),'"',
				' imageFieldName="',this.configurations["imageFieldName"],'"'
			   ].join("");
	}
	return str;
}

OtaSwfUploader.prototype._getParameters = function()
{
	var str = ['movieName=', encodeURIComponent(this.movieName),
				'&amp;buttonLabel=', encodeURIComponent(this.configurations["buttonLabel"]),
				'&amp;postUrl=',encodeURIComponent(this.configurations["postUrl"]),
				'&amp;allowMultiplesFiles=',encodeURIComponent((this.configurations["allowMultiplesFiles"]?"true":"false")),
				'&amp;imageFieldName=',encodeURIComponent(this.configurations["imageFieldName"]),
			   ].join("");
	
	return str;
}

OtaSwfUploader.prototype.addFileParameter = function(id, key, value)
{
	var flashObject = this._getFlashObject();
	
	if(flashObject)
		flashObject.addFileParameter(id,key,value);
}

OtaSwfUploader.prototype.getNumberOfFiles = function()
{
	var flashObject = this._getFlashObject();
	
	if(flashObject){
		return flashObject.getNumberOfFiles();		
	}
	
	return 0;
}

OtaSwfUploader.prototype.getNumberOfPendingFiles = function()
{
	var flashObject = this._getFlashObject();
	
	if(flashObject){
		return flashObject.getNumberOfPendingFiles();		
	}
	
	return 0;	
}

OtaSwfUploader.prototype.resetFiles = function()
{
	var flashObject = this._getFlashObject();
	
	if(flashObject){
		flashObject.resetFiles();
		return true;
	}
	
	return false;		
}

OtaSwfUploader.prototype.startUpload = function(fileId)
{
	var flashObject = this._getFlashObject();
	
	if(flashObject){
		var fn = function(){
			flashObject.startUpload(fileId);		
		}
		window.setTimeout(fn,400);
	}
}

OtaSwfUploader.prototype.startNextPendingFile = function()
{
	var flashObject = this._getFlashObject();
	
	if(flashObject){
		return flashObject.startNextPendingFile();
	}
	
	return false;
}

OtaSwfUploader.prototype.getFileStatus = function(fileId)
{
	var flashObject = this._getFlashObject();
	
	if(flashObject){
		return flashObject.getFileStatus();
	}
	
	return null;
}

OtaSwfUploader.prototype.cancelFileUpload = function(fileId)
{
	var flashObject = this._getFlashObject();
	
	if(flashObject){
		return flashObject.cancelFileUpload(fileId);
	}
	
	return false;	
}

OtaSwfUploader.prototype.addFileFilter = function(str_label,str_filter)
{
	var flashObject = this._getFlashObject();
	
	if(flashObject){
		flashObject.addFileFilter(str_label,str_filter);
		return true;
	}
	
	return false;	
}
/*
 * Events sended to us by flash
 */
OtaSwfUploader.prototype.onPendingFileAdded = function(movieName,fileInfo)
{
}

OtaSwfUploader.prototype.onUploadNotify = function(fileId, status, info)
{
}

OtaSwfUploader.prototype.onInitPlugin = function()
{
}

/*
 * End of events
 */